export default {
  mounted(el, binding) {
    let timer = null;
    let isPress = false; // 长按状态标志
    let isDown = false; // 按下状态标志
    let longFn = null; // 长按处理函数
    let clickFn = null; // 点击处理函数
    let interTimer = null;
    let num = 500;
    let interNum = 100;
    const isInter = binding?.arg?.includes(":") ?? false;
    if (isInter) {
      const [subBefore, subAfter] = binding.arg.split(":");
      num = Number(subBefore);
      interNum = Number(subAfter);
    } else if (binding.arg) {
      num = Number(binding.arg);
    }
    // 根据传入的参数确定长按和点击函数
    if (Array.isArray(binding.value)) {
      [longFn, clickFn] = binding.value;
    } else if (typeof binding.value === 'function') {
      longFn = binding.value;
    }
    const onDownInter = (ev) => {
      ev.preventDefault();
      if (interTimer === null) {
        interTimer = setInterval(() => longFn?.(ev), interNum);
      }
    };
    const startPress = (event) => {
      isPress = false; // 重置状态
      isDown = true;

      timer = setTimeout(() => {
        isPress = true; // 设置为长按状态
        longFn?.(event); // 调用长按事件处理函数
        if (isInter) {
          onDownInter(event)
        }
      }, num); // 使用指令参数，默认为500ms
    };

    const endPress = (event) => {
      clearTimeout(timer);
      if (isInter) {
        clearInterval(interTimer)
        interTimer = null
      }
      if (!isPress && isDown) {
        // 只有在没有长按的情况下才触发点击事件
        clickFn?.(event);
        isDown = false; // 重置按下状态
      }
    };

    el.addEventListener('mousedown', startPress);
    el.addEventListener('mouseup', endPress);
    el.addEventListener('mouseleave', endPress);

    // 在指令解绑时移除事件监听
    el._longpressCleanup = () => {
      el.removeEventListener('mousedown', startPress);
      el.removeEventListener('mouseup', endPress);
      el.removeEventListener('mouseleave', endPress);
    };
  },
  unmounted(el) {
    el._longpressCleanup();
  }
};
